import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import { codeStatus } from '@/utils/constants'
import Vue from 'vue'
import localCache from '@/utils/localCache'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    config.headers['Authorization'] = getToken()
    if (config.responseType === 'blob') {
      config.headers.responseType = 'arraybuffer'
      config.headers.Accept = 'application/json'
      config.headers.ContentType = 'application/json; charset=utf-8'
    } else {
      config.headers['Content-Type'] = 'application/json-patch+json'
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log('error->', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data

    // console.log('响应拦截器', res)
    // console.log('响应拦截器', response)
    if (res.code === 406) {
      Message.error('账户已登出')
      logOut()
      return
    }
    // if the custom code is not 20000, it is judged as an error.
    /*  if (res.code !== 0) {
       Message({
         message: res.msg || 'Error',
         type: 'error',
         duration: 5 * 1000
       })
       // 鉴权失败，跳转登录页面
       if (codeStatus.LOGIN_ERR === res.code || codeStatus.AUTH_ERR === res.code) {
         removeToken();
       }
       return Promise.reject(new Error(res.message || 'Error'))
     } else {
       return res
     } */
    return res
  },
  (error) => {
    // console.log(error.response) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    if (error.response.status === 401) {
      Message.error('登录令牌已过期')
      logOut()
      return
    }
    return Promise.reject(error)
  }
)

export function baseUpload(urls, data) {
  const baseURL = process.env.VUE_APP_BASE_API
  const loading = Vue.prototype.$loading({
    lock: true,
    text: '上传中',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return new Promise((resolve, reject) => {
    const form = new FormData()
    for (const key in data) {
      form.append(key, data[key])
    }
    axios
      .post(baseURL + urls, form, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: getToken()
        },
        transformRequest: [
          function (data) {
            return data
          }
        ]
      })
      .then(
        (response) => {
          loading.close()
          resolve(response.data)
        },
        (err) => {
          loading.close()
          reject(err)
        }
      )
  })
}

async function logOut() {
  await store.dispatch('tenant/logout')
  router.push(`/login`)
  store.commit('m_msg/WEBSOCKET_CLOSED')
  removeToken()
  window.location.reload()
}

export default service
